import { api } from "./api";

let shopRows = null;
let homeTip = null;
let shopMap = {};

export async function onShopHook(body) {
  const { name, row } = body;
  let sid = row.sid;
  if (name == "config-change") {
    homeTip = null;
  } else if (name == "shop-change") {
    shopRows = null;
    sid = row.id;
  }
  if (sid) {
    delete shopMap[sid * 1];
  }
}

export async function getShopList() {
  if (!shopRows) {
    console.log("get shops");
    shopRows = await api.getShops({});
  }
  return shopRows;
}

export async function getShopHome(body) {
  if (!homeTip) {
    const config = await api.getData("item", "mp-config", { id: 1 });
    if (config) homeTip = config.desc;
  }
  let shops = await getShopList();
  let { ids } = body;
  if (ids) {
    ids = ids.split(",");
    shops = shops.filter((it) => ids.includes(it.id + ""));
  }
  return {
    homeTip,
    shops,
  };
}

export async function getShopInfo(sid) {
  const list = await getShopList();
  const row = list.find((it) => it.id == sid);
  return (
    row || {
      name: "门店" + sid,
    }
  );
}

export async function fillShopName(rows) {
  const shops = await getShopList();
  if (!Array.isArray(rows)) {
    rows = [rows];
  }
  for (const row of rows) {
    if (!row.sid) continue;
    const shop = shops.find((it) => it.id == row.sid);
    row.shopName = shop?.name || "门店" + row.sid;
  }
}

export async function getShopDetail(body) {
  const sid = body.id * 1;
  if (!sid) {
    throw "缺少参数";
  }
  let row = shopMap[sid];
  if (row) {
    return row;
  }
  row = await api.getShopRow(body, "/data/item/shop-user");
  if (!row) throw "店铺信息不存在";
  row.banners = await api.getBannerList({
    sid,
  });
  if (row.on) {
    row.goods = await api.getGoodsList({ sid });
  }
  shopMap[sid] = row;
  return row;
}

export async function getBanners(body) {
  return api.getBannerList(body);
}

export async function getGoodsList(body) {
  body._data = 1;
  return api.getGoodsList(body);
}

export async function getGoodsInfo(body) {
  const row = await api.getGoodsRow(body);
  if (!row) throw "商品信息不存在";
  row.shop_info = await getShopInfo(row.sid);
  return row;
}
